package the.one.weather.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.VideoView;

import com.luck.picture.lib.permissions.RxPermissions;
import com.qmuiteam.qmui.widget.QMUIViewPager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import the.one.base.base.activity.BaseActivity;
import the.one.base.base.presenter.BasePresenter;
import the.one.base.util.EventBusUtil;
import the.one.base.widge.MyTopBarLayout;
import the.one.weather.R;
import the.one.weather.event.AddEvent;
import the.one.weather.event.ChangedEvent;
import the.one.weather.event.ScrollEvent;
import the.one.weather.model.Weather;
import the.one.weather.ui.adapter.WeatherPagerAdapter;
import the.one.weather.ui.fragment.WeatherItemFragment;
import the.one.weather.util.LitePalUtil;
import the.one.weather.util.ViewPagerUtil;


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛

/**
 * @author The one
 * @date 2019/5/7 0007
 * @describe 主界面
 * @email 625805189@qq.com
 * @remark
 */
public class Weather2Activity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.view_pager)
    QMUIViewPager mViewPager;
    @BindView(R.id.video_view)
    VideoView mVideoView;

    @BindView(R.id.qmui_top_bar_layout)
    MyTopBarLayout mTopBarLayout;
    @BindView(R.id.radio_group)
    RadioGroup mRadioGroup;
    @BindView(R.id.separator)
    View mSeparator;

    private Button mCityName;
    private Button mTemp;

    private List<WeatherItemFragment> mWeatherFragments;
    private List<Weather> mCityWeatherList;
    private WeatherPagerAdapter mPageAdapter;

    /**
     * 当前Fragment位置
     */
    private int mIndex = 0;

    /**
     * 当前背景的透明度百分比
     */
    private float mCurrentBgAlphaPercent;

    /**
     * 当前播放的视频
     */
    private int mCurrentVideo;

    /**
     * 当前滑动的距离信息
     */
    private ScrollEvent mScrollEvent;

    @Override
    protected void initView(View rootView) {
        requestPermission();
    }

    private void requestPermission() {
        final RxPermissions permissions = new RxPermissions(this);
        permissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_WIFI_STATE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // 数据库
                        SQLiteDatabase db = Connector.getDatabase();
                        LitePalUtil.writeCityData(Weather2Activity.this);
                        initTopBarCityName();
                        initViewPager();
                        initData(LitePalUtil.getAllWeatherCities());
                    }
                });
    }

    public void initTopBarCityName() {
        mCityName = mTopBarLayout.addLeftTextButton("", R.id.topbar_left_text);
        mTemp = mTopBarLayout.addLeftTextButton("", R.id.topbar_left_button);
        goneView(mTemp,mCityName);
        mTopBarLayout.addRightImageButton(R.drawable.mz_titlebar_add_dark, R.id.topbar_right_button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(CityManagerActivity.class);
            }
        });
        mTopBarLayout.setBackgroundAlpha(0);
        updateBgAlpha(0);
    }

    private void initViewPager() {
        mViewPager.setOffscreenPageLimit(10);
        mViewPager.addOnPageChangeListener(this);
    }

    /**
     * @TODO 滑动时处理透明度
     * @param i
     * @param percent
     * @param offset
     * @remark 如何解决自动回滚时的距离百分比？
     */
    @Override
    public void onPageScrolled(int i, float percent, int offset) {
        // 判断是左滑还是右滑
        boolean isRight = mIndex != i;
        // 如果是右滑 百分比是从大到小 需要进行处理
        if (isRight) {
            percent = 1 - percent;
        }
        // 为了滑到一半的时候就让整个背景变为白色，这里做双倍处理
        percent = percent * 2;
        // 超过1了就为1处理
        if (percent > 1) percent = 1;
        // 当前百分比不一致才进行背景变化
        if (mCurrentBgAlphaPercent <= percent) {
            updateBgAlpha(percent);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onPageSelected(int i) {
        mIndex = i;
        RadioButton rb = (RadioButton) mRadioGroup.getChildAt(mIndex);
        rb.setChecked(true);
        Weather weather = getWeatherFragment(mIndex).getWeather();
        if (null != weather) {
            mCityName.setText(weather.getCurrentCity());
            mTemp.setText(weather.getTemperature() + "°");
        } else {
            mCityName.setText(mCityWeatherList.get(i).getCurrentCity());
        }

        //ViewHelper.fadeOut(mRadioGroup, 3000, null, true); // 是否要淡出
    }

    @Override
    public void onPageScrollStateChanged(int i) {
        //0：什么都没做 1：开始滑动 2：滑动结束
        if (i == 0) {
            // 滑动到一半停止了，返回到了原来的位置，此时要把背景设为透明
            updateBgAlpha(0);
        }
    }

    /**
     * @TODO 初始化数据
     * @remark 数据有变化时直接调用整个方法
     */
    private void initData(List<Weather> weathers) {
        goneVideoView();
        mCityWeatherList = weathers;
        if (null == mCityWeatherList || mCityWeatherList.size() == 0) {
            startActivity(CityManagerActivity.class);
            return;
        }
//        mCurrentBgAlphaPercent = 0.0f;
        mCurrentVideo = 0;
        mScrollEvent = new ScrollEvent(0, 0);
        mWeatherFragments = new ArrayList<>();
        for (int i = 0; i < mCityWeatherList.size(); i++) {
            mWeatherFragments.add(WeatherItemFragment.newInstance(mCityWeatherList.get(i)));
        }
        // 在获取到数据后才初始化指示器
        initIndicator();
        ViewPagerUtil.clear(mViewPager, getSupportFragmentManager());
        mPageAdapter = new WeatherPagerAdapter(getSupportFragmentManager());
        mPageAdapter.setWeatherFragmentList(mWeatherFragments);
        mViewPager.setAdapter(mPageAdapter);
        onPageSelected(mIndex);
        showView(mCityName);
    }

    /**
     * 更改主背景透明度
     *
     * @param percent
     * @remark 左右滑动的时候背景会有一会百分比向白色转变的过程。这里直接更改ViewPager的背景透明度
     */
    public void updateBgAlpha(float percent) {
        mCurrentBgAlphaPercent = percent;
        float alpha = (255 * percent);
        mViewPager.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
    }

    /**
     * 初始化指示器
     */
    private void initIndicator() {
        mRadioGroup.removeAllViews();
        for (int i = 0; i < mCityWeatherList.size(); i++) {
            RadioButton tempButton = new RadioButton(this);
            tempButton.setBackgroundResource(mCityWeatherList.get(i).isLbs() ? R.drawable.dot_lbs_selector : R.drawable.dot_selector);
            tempButton.setButtonDrawable(null);
            mRadioGroup.addView(tempButton, 25, 25);
        }
    }

    public ScrollEvent getScrollEvent() {
        return mScrollEvent;
    }

    public void onScroll(ScrollEvent event) {
        if (null != event)
            mScrollEvent = event;
        if (null == mScrollEvent) return;
        mTopBarLayout.setBackgroundAlpha(event.getPercent());
        if (event.isMaxPercent()) {
            showView(mTemp, mSeparator);
        } else {
            goneView(mTemp, mSeparator);
        }
        // 移动相邻的两个
        int left = mIndex - 1;
        int right = mIndex + 1;
        // 检查是否在范围内
        if (left >= 0) scrollTo(left);
        if (right < mCityWeatherList.size()) scrollTo(right);
    }

    @SuppressLint("SetTextI18n")
    public void playWeatherVideo(Weather weather) {
        if (null == weather || null == mCityWeatherList || TextUtils.isEmpty(weather.getWeather()))
            return;
        if (mCityWeatherList.get(mIndex).getCurrentCity().equals(weather.getCurrentCity())) {
            mTemp.setText(weather.getTemperature() + "°");
            int video = weather.getWeatherVideo();
            goneVideoView();
//            if (mCurrentVideo != video) {
            final String uri = "android.resource://" + getPackageName() + "/" + video;
            mCurrentVideo = video;
            mVideoView.setVideoPath(uri);
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.setVolume(0, 0);
                    mediaPlayer.start();
                    mediaPlayer.setLooping(true);
                }
            });
            mVideoView.requestFocus();
            mVideoView.start();
            showVideoView();
//            } else {
//                updateBgAlpha(0);
//            }
        }
    }

    private void showVideoView() {
        updateBgAlpha(0);
        showView(mVideoView);
    }

    private void goneVideoView() {
        updateBgAlpha(1);
        goneView(mVideoView);
    }

    private void scrollTo(int index) {
        WeatherItemFragment fragment = getWeatherFragment(index);
        fragment.scrollTo(mScrollEvent);
    }

    private Handler mHandler = new Handler();
    private Runnable mRunnable;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAdd(AddEvent event) {
        EventBusUtil.removeStickyEvent(event);
        String addCity = event.getWeatherCity();
        //  这里是从搜索城市点击后返回来的，先检查选择的城市是否已经存在，如果存在就直接跳到该城市界面
        for (int i = 0; i < mCityWeatherList.size(); i++) {
            if (addCity.equals(mCityWeatherList.get(i).getCurrentCity())) {
                setCurrentFragment(i);
                return;
            }
        }
        // 如果没有再进行保存，保存成功后重构一遍
        if (LitePalUtil.saveNormalCityWeather(addCity)) {
            // 添加的城市直接指向最后一个
            mCityWeatherList = LitePalUtil.getAllWeatherCities();
            mIndex = mCityWeatherList.size() - 1;
            initData(mCityWeatherList);
            setCurrentFragment(mIndex);
        }
    }

    private void setCurrentFragment(final int index) {
        mViewPager.setCurrentItem(index, false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChanged(ChangedEvent event) {
        List<Weather> weathers = event.getWeatherCity();
        EventBusUtil.removeStickyEvent(event);
        goneVideoView();
        boolean isChanged = false;
        // 如果当前为空或者数量为0或者数量前后不相同(删除过)则要重新创建
        if (null == mCityWeatherList || mCityWeatherList.size() == 0 || weathers.size() != mCityWeatherList.size()) {
            isChanged = true;
        } else {
            // 数量一样再判断顺序是否一样
            for (int i = 0; i < weathers.size(); i++) {
                // 顺序不一样也要重新创建
                String after = weathers.get(i).getCurrentCity();
                String before = mCityWeatherList.get(i).getCurrentCity();
                if (!after.equals(before)) {
                    isChanged = true;
                    break;
                }
            }
        }
        if (isChanged) {
            mIndex = 0;
            initData(weathers);
            setCurrentFragment(mIndex);
        }else{
            showVideoView();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(null != mVideoView && mVideoView.canPause()){
            mVideoView.pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(null != mVideoView){
            mVideoView.resume();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mHandler) {
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
            mHandler = null;
        }
    }

    private WeatherItemFragment getWeatherFragment(int index) {
        return (WeatherItemFragment) mPageAdapter.createFragment(index);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_index;
    }

    @Override
    protected boolean isExitActivity() {
        return true;
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

}
